package com.w.picture.manager.upload;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.*;
import com.w.picture.exception.BusinessException;
import com.w.picture.exception.ErrorCode;
import com.w.picture.exception.ThrowUtils;
import com.w.picture.mode.enums.FileUploadBizEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;

/**
 * @Title: UrlPictureUpload
 * @Author wzp
 * @Date 2025/1/9 10:31
 * @description: URL类型图片上传
 */
@Slf4j
@Component
public class UrlPictureUpload extends PictureUploadTemplate {
    @Override
    public void validPicture(Object inputSource, FileUploadBizEnum bizEnum) {
        if (inputSource instanceof String) {
            String fileUrl = (String) inputSource;
            ThrowUtils.throwIf(StrUtil.isBlank(fileUrl), ErrorCode.PARAMS_ERROR, "文件地址不能为空");
            try {
                // 1. 验证 URL 格式
                new URL(fileUrl); // 验证是否是合法的 URL
            } catch (MalformedURLException e) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR.getCode(), "文件地址格式不正确");
            }

            // 2. 校验 URL 协议
            ThrowUtils.throwIf(!(fileUrl.startsWith("http://") || fileUrl.startsWith("https://")),
                    ErrorCode.PARAMS_ERROR, "仅支持 HTTP 或 HTTPS 协议的文件地址");

            // 3. 发送 HEAD 请求以验证文件是否存在
            HttpResponse response = null;
            try  {
                HttpRequest request = HttpUtil.createRequest(Method.HEAD, fileUrl);
                response = request.execute();
                // 未正常返回，无需执行其他判断
                if (response.getStatus() != HttpStatus.HTTP_OK) {
                    return;
                }
                // 4. 校验文件类型
                String contentType = response.header("Content-Type");
                if (StrUtil.isNotBlank(contentType)) {
                    // 允许的图片类型
                    final List<String> ALLOW_CONTENT_TYPES = Arrays.asList("image/jpeg", "image/jpg", "image/png", "image/webp");
                    ThrowUtils.throwIf(!ALLOW_CONTENT_TYPES.contains(contentType.toLowerCase()),
                            ErrorCode.PARAMS_ERROR, "文件类型错误");
                }
                // 5. 校验文件大小
                String contentLengthStr = response.header("Content-Length");
                if (StrUtil.isNotBlank(contentLengthStr)) {
                    try {
                        long contentLength = Long.parseLong(contentLengthStr);
                        final long TWO_MB = 2 * 1024 * 1024L; // 限制文件大小为 2MB
                        ThrowUtils.throwIf(contentLength > TWO_MB, ErrorCode.PARAMS_ERROR, "文件大小不能超过 2M");
                    } catch (NumberFormatException e) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR.getCode(), "文件大小格式错误");
                    }
                }
            }catch (Exception e){
                log.error("图片校验异常",e);
            }finally {
                if (response != null){
                    response.close();
                }
            }
        }

    }

    @Override
    protected String getOriginFilename(Object inputSource) {
        if (inputSource instanceof String) {
            String url = (String) inputSource;
            return FilenameUtils.getName(url);
        }
        return "";
    }

    @Override
    protected void processFile(Object inputSource, File file) throws IOException {
        if (inputSource instanceof String) {
            String url = (String) inputSource;
            HttpUtil.downloadFile(url, file);
        }
    }
}
